import { createRouter, createWebHistory } from 'vue-router'
import LayOut from '_views/LayOut'
import { isLogin } from '@/utils/user'
import { getRole } from '@/utils'
const routes = [
  {
    path: '/',
    name: 'LayOut',
    component: LayOut,
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      },
      {
        path: '/dashBoard',
        name: '首页',
        meta: { roles: '*' },
        component: () => import('_views/DashBoard')
      },
      {
        path: '/nowPage',
        name: '在学学员',
        meta: { roles: ['admin', 'a'] },
        component: () => import('_views/NowPage')
      },
      {
        path: '/userInfo',
        name: '个人中心',
        meta: { roles: ['admin', 'a'] },
        component: () => import('_views/UserInfo')
      },
      {
        path: '/setting',
        name: '设置',
        meta: { roles: ['admin'] },
        component: () => import('_views/SettingPage')
      },
      {
        path: '/wantPage',
        name: '意向学员',
        meta: { roles: ['admin'] },
        component: () => import('_views/WantPage')
      },
      {
        path: '/endPage',
        name: '结业学员',
        meta: { roles: ['admin'] },
        component: () => import('_views/EndPage')
      },
      {
        path: '/studyUpdate',
        name: '学员详情',
        meta: { roles: ['admin'] },
        component: () => import('_views/StudyUpdate')
      }
    ]
  },
  {
    path: '/login',
    name: '登录',
    meta: { roles: '*' },
    component: () => import('_views/LoginPage')
  },
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    meta: { roles: '*' },
    component: () => import('_views/NoFound')
  },
  {
    path: '/noPermission',
    name: '没有权限',
    meta: { roles: '*' },
    component: () => import('_views/NoPermission')
  }

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const passRoutes = ['/login']
  if (passRoutes.includes(to.path)) {
    next()
  } else {
    // 非登录页 鉴权
    if (isLogin()) {
      // 判断 角色是否可以访问该路由
      if (to.meta.roles === '*' || to.meta.roles.includes(getRole())) {
        // 可以访问
        next()
      } else {
        next('/noPermission')
      }
    } else {
      next('/login')
    }
  }
})
export default router
